import $ from '@/common'
import Time from '@/common/time'

var defaultOption = {
  title: {
    show: false
  },
  // hover显示的数据说明
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      // type: 'shadow',
      // color: 'rgba(200,200,200,0.1)',
      // opacity: 0.3
    }
  },
  // 图例
  legend: {
    top: 0,
    right: 0,
    // orient: 'vertical',
    data: [],
    selected: {}
  },
  // 整体表格布局
  /** */
  grid: [{
    containLabel: true,
    top: 50,
    left: 0,
    right: 0,
    bottom: 20
  }],
  xAxis: [{
    type: 'category',
    nameTextStyle: {
      fontStyle: 10
    },
    axisLabel: {
      // interval: 0,
      /* 
      //旋转位置配置
      rotate: 45,
      margin: 2
      */
      // 竖排显示配置
      /*
        formatter: function (value) {
          return value.split('').join('\n')
        }
        */
    },
    data: []
  }],
  axisPointer: {
    link: {
      xAxisIndex: 'all'
    }
  },
  /*
  //滚动缩放
  dataZoom: [{
    type: 'inside'
  }],
  */
  yAxis: [],
  series: []
}

function modelLines(model, tab = 0) {
  var lines = model.lines
  var linesList = {}
  for (let i = 0; i < lines.length; i++) {
    linesList[lines[i].code] = lines[i]
  }
  if (model.tabs && model.tabs[tab]) {
    lines = []
    let tabData = model.tabs[tab]
    if (tabData.all_lines) {
      lines = model.lines
    } else {
      for (let i in tabData.item) {
        if (linesList[tabData.item[i]]) {
          lines.push(linesList[tabData.item[i]])
        }
      }
    }
  }
  return lines
}
//生成y轴数据
function makeYaxis(option, model, gridIndex, tab) {
  var lines = modelLines(model, tab)
  for (let i = 0; i < lines.length; i++) {
    var line = lines[i]
    option.legend.data.push(line.name)
    if (!option.legend.show) {
      option.legend.show = {}
    }
    if (i > 0 && !line.show) {
      option.legend.selected[line.name] = false
    }
    if (model.legend === false) {
      option.legend.show[line.name] = false
    }
    //临时处理，只设置主y轴 当设置多个y轴时隐藏的y轴依旧会占用空间
    //需根据处理设置y轴切换逻辑和外部方法（通过setOption merge 跟新y轴）
    var new_y_index = 0
    if (i === 0 || (line.attach === undefined && line.y_index === undefined)) {
      option.yAxis.push({
        show: i === 0 || line.y_show,
        gridIndex: gridIndex || 0,
        type: 'value',
        name: line.y_show !== undefined ? line.name : model.y_name || line.name,
        nameLocation: 'end',
        // 不显示间隔线
        splitLine: {
          show: false
        },
        nameTextStyle: {
          color: '#666'
        },
        axisLabel: {
          formatter: value => {
            if (line.format === 'percent') {
              value = (parseFloat(value) * 100).toFixed(2) + '%'
            }
            if (line.format === 'money') {
              value = $.toMoney(value)
            }
            return value
          }
        },
        rich: {}
      })
      new_y_index = option.yAxis.length - 1
    }

    var y_index = (line.stack ? null : (line.attach !== undefined ? line.attach : i))
    if (line.y_index !== undefined) {
      y_index = line.y_index
    }
    if (new_y_index !== 0) {
      y_index = new_y_index
    }

    var series = {
      name: line.name,
      clipOverflow: false,
      type: line.type || 'bar',
      label: {
        normal: {
          show: line.show_value !== false,
          position: 'top',
          // 显示设置点位
          formatter: line.unit ? '{c}' + line.unit : null,
          offset: line.label_offset
        }
      },
      // 通过attch设置依附的系列
      xAxisIndex: gridIndex,
      yAxisIndex: y_index,
      barGap: line.attach !== undefined ? '-100%' : null,
      data: [],
      itemStyle: {
        normal: {
          color: line.color
        }
      },
      stack: line.stack,
      format: line.format,
      unit: line.unit
    }
    // 显示平局值线
    if (line.average) {
      series.markLine = {
        data: [{
          type: 'average',
          name: '平均值',
          label: {
            normal: {
              show: true,
              position: 'middle',
              formatter({
                value
              }) {
                if (line.format === 'money') {
                  value = parseFloat(value) || 0
                  value = $.toMoney(value.toFixed(2));
                }
                return `平均值 : ${value}`
              }
            }
          }
        }]
      }
    }
    option.series.push(series)
  }
}
const dayName = ['日', '一', '二', '三', '四', '五', '六']
export default {
  model(model, tab) {
    var option = $.copy(defaultOption)
    //初始化xy轴
    var grids = [model, ...model.grids || []]
    for (let i = 0; i < grids.length; i++) {
      var grid = grids[i]
      var fields = []
      for (let j = 0; j < grid.fields.length; j++) {
        let field = grid.fields[j]
        fields[field.code] = field
      }
      var xField = fields[grid.x_axis]
      option.grid = $.setObj(option.grid, model.grid)
      if (!option.xAxis[i]) {
        option.xAxis.push({
          type: 'category',
          gridIndex: i,
          axisLabel: {},
          data: []
        })
      }
      if (!option.grid[i]) {
        option.grid.push({})
      }
      option.grid[i] = $.setObj(grid.grid || {}, option.grid[i])
      if (xField) {
        let axisLabel = option.xAxis[i].axisLabel
        axisLabel.interval = 0
        // x轴竖排显示
        if (xField.vertical) {
          axisLabel.formatter = function (value) {
            return value.split('').join('\n')
          }
        }
      }
      makeYaxis(option, grid, i, tab)
    }
    return option
  },
  data(model, data, option, tab, gridIndex = 0, xData) {
    var x = model.x_axis
    var tabBranch = null
    data = $.copy(data).sort((a, b) => {
      return a[x] > b[x] ? 1 : -1
    })
    option.xAxis[gridIndex].data = []
    var fields = {}
    for (let i in model.fields) {
      let field = model.fields[i]
      fields[field.code] = field
    }
    var xField = fields[model.x_axis]
    for (let j = 0; j < option.series.length; j++) {
      var s = option.series[j]
      if ((option.yAxis[s.yAxisIndex || 0].gridIndex || 0) === gridIndex) {
        s.data = []
      }
    }
    var x_list = {}
    var x_count = 0
    for (let i = 0; i < data.length; i++) {
      let v = data[i]
      // 数据格式化
      for (let k in model.fields) {
        let field = model.fields[k]
        let value = v[field.code]
        if (value && field.type === 'date' && field.type_ts) {
          value = Time.toDate(value)
        }
        if (value && field.type === 'date' && value.length > 8) {
          let arr = value.split('-')
          let dt = new Date(Time.toTs(value))
          arr.shift()
          v[field.code] = arr.join('/')
          v[field.code + '_day'] = dt.getDay()
        }
      }
    }
    option.tooltip.formatter = function (params) {
      if (!$.isArray(params)) {
        params = [params]
      }
      var content = null
      for (let line of params) {
        if (!content) {
          let axisValue = line.axisValue
          if (data[line.dataIndex] && data[line.dataIndex][x + '_day'] !== undefined) {
            if (data[line.dataIndex][x + '_day'] === 0 || data[line.dataIndex][x + '_day'] === 6) {
              axisValue += `&nbsp;&nbsp;<span style="color:#f18686;">周${dayName[data[line.dataIndex][x + '_day']]}</span>`
            } else {
              axisValue += `&nbsp;&nbsp;周${dayName[data[line.dataIndex][x + '_day']]}`
            }
          }
          content = `${axisValue}${model.labelText || ''}</br><table>`
        }
        var value = line.value
        var serie = option.series[line.seriesIndex]
        //TODO 判断字段类型进行格式化
        if (serie && serie.format === 'money') {
          value = $.toMoney(value)
        }
        if (serie && serie.format === 'percent') {
          value = value * 100 + '%'
        }
        if (serie && serie.unit) {
          value = value + '' + serie.unit
        }
        content += `<tr><td>${line.marker}</td><td>${line.seriesName}&nbsp;&nbsp;</td><td>${value}</td></tr>`
      }
      if (content) {
        content += '</table>'
      }
      return content
    }
    //生成x轴数据
    if (!gridIndex) {
      for (let i = 0; i < data.length; i++) {
        let v = data[i]
        // 整理x轴数据，使用x_list记录x轴数据需要，以做数据对应
        var vx = v[x]
        if (vx === undefined && xField.default !== undefined) {
          vx = xField.default
        }
        if (x_list[vx] === undefined) {
          x_list[vx] = x_count
          //日期类型对周末进行标识
          if (xField && xField.type === 'date') {
            if (v[xField.code + '_day'] === 0 || v[xField.code + '_day'] === 6) {
              option.xAxis[gridIndex].data.push({
                value: vx,
                textStyle: {
                  color: '#bbb'
                }
              })
            } else {
              option.xAxis[gridIndex].data.push({
                value: vx,
                textStyle: {
                  color: '#555'
                }
              })
            }
          } else {
            option.xAxis[gridIndex].data.push(vx)
          }
          x_count++
        }
      }
    } else {
      option.xAxis[gridIndex].data = option.xAxis[0].data
    }
    //控制x轴最大数量
    option.xAxis[gridIndex].axisLabel = option.xAxis.axisLabel || {}
    option.xAxis[gridIndex].axisLabel.interval = 'auto'
    if (gridIndex) {
      option.xAxis[gridIndex].axisLabel.show = false
    }

    //设置显示的line，若有tab则显示tab，若无则显示所有line
    var lines = modelLines(model, tab)
    var linesMap = {}
    for (let i in lines) {
      linesMap[lines[i].name] = lines[i]
    }
    if (model.tabs && model.tabs[tab]) {
      tabBranch = model.tabs[tab].branch
    }

    for (let i = 0; i < data.length; i++) {
      let v = data[i]
      // 循环line，加入线的数据
      for (let j = 0; j < option.series.length; j++) {
        let l = linesMap[option.series[j].name]
        if (!l) {
          continue
        }
        let value = v[l.code]
        // 分支型线判断数据
        let branch = null
        if (tabBranch || l.branch) {
          branch = {
            ...l.branch || {},
            ...tabBranch || {}
          }
        }
        if (branch) {
          var c = true
          for (let k in branch) {
            if ((v[k] !== branch[k]) && (branch[k] !== null || (branch[k] === null && v[k] !== undefined))) {
              c = false
              break
            }
          }
          if (c && x_list[v[x]] !== undefined) {
            option.series[j].data[x_list[v[x]]] = value
          }
        } else {
          option.series[j].data.push(value)
        }
      }
    }
    // 补全缺失数据
    for (let i = 0; i < option.series.length; i++) {
      let s = option.series[i]
      if ((option.yAxis[s.yAxisIndex || 0].gridIndex || 0) === gridIndex) {
        for (let j = 0; j < x_count; j++) {
          if (s.data[j] === undefined || s.data[j] === null) {
            s.data[j] = 0
          }
        }
      }
    }
    return option
  }
}
